package xyz.zhouxf.rpc.util;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.List;


/**
 * @author zhouxf
 * @date 2022/9/2
 */
@Slf4j
public class NacosUtil {

    private static InetSocketAddress nacosAddr;

    private static final NamingService namingService;

    private static final String NACOS_SERVER_ADDR = "127.0.0.1:8848";


    static {
        namingService = getNacosNamingService();
    }

    public static NamingService getNacosNamingService() {
        try {
            return NamingFactory.createNamingService(NACOS_SERVER_ADDR);
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void registerService(String serviceName, InetSocketAddress serviceAddr) throws NacosException {
        namingService.registerInstance(serviceName, serviceAddr.getHostName(), serviceAddr.getPort());
    }

    public static List<Instance> getAllInstances(String serviceName) throws NacosException {
        return namingService.getAllInstances(serviceName);
    }
}
